package com.tang.thepath.util;

import android.content.Context;
import android.os.PowerManager;
import android.util.Log;

/**
 * Created by Tangyanjun
 * Date 2018/2/11
 * Email 312976625@qq.com
 */

public class WakeLockManager {
    public final static String TAG = "WakeLockManager";
    private static WakeLockManager instance = null;
    private PowerManager.WakeLock wakeLock = null;

    private WakeLockManager(){
    }



    public static WakeLockManager getInstance() {
        if (instance == null) {
            synchronized (WakeLockManager.class) {
                if (instance == null) {
                    instance = new WakeLockManager();
                }
            }
        }
        return instance;
    }



    /**
     * 获取电源锁，保持该服务在屏幕熄灭时仍然获取CPU时，保持运行
     */
    public void acquire(Context context) {
        if (null == wakeLock) {
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK
                    | PowerManager.ON_AFTER_RELEASE, context.getClass()
                    .getCanonicalName());

            wakeLock.acquire();
            Log.i(TAG ,"call acquireWakeLock");
        }
    }



    // 释放设备电源锁
    public void release() {
        if (null != wakeLock && wakeLock.isHeld()) {
            Log.i(TAG, "call releaseWakeLock");
            wakeLock.release();
            wakeLock = null;
        }
    }
}
